<template>
  <div>
    <div class="upload-list">
      <template v-for="(item, index) in imagesList" :key="index">
        <div class="upload-item">
          <image
            :src="item"
            class="upload-item-img"
            mode="aspectFill"
            bindtap="predivImage"
          />
          <div
            class="upload-item-del icon icon-cuo"
            @click="deleteImage(index)"
          ></div>
        </div>
      </template>
      <div
        class="upload-item"
        v-if="imagesList.length < maxCount || !imagesList"
      >
        <div class="upload-item-btn">
          <div class="icon icon-shangchuan" @click="chooseImage"></div>
        </div>
      </div>
    </div>
  </div>
</template>


<script lang="ts">
export default {
  name: "upload-list",
};
</script>
<script lang="ts" setup>
import { ref, getCurrentInstance } from "vue";

const {
  proxy: { $utils },
} = getCurrentInstance() as any;

const props = withDefaults(
  defineProps<{
    maxCount?: number;
  }>(),
  {
    maxCount: 9,
  }
);

const emit = defineEmits(["change"]);

const imagesList = ref<any>([]);

const chooseImage = () => {
  let _imageList = imagesList.value || [];
  uni.chooseImage({
    count: props.maxCount - _imageList.length,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: function (res) {
      imagesList.value = _imageList.concat(res.tempFilePaths);
      emit("change", imagesList.value);
    },
  });
};

const deleteImage = (index: number) => {
  let _imageList = imagesList.value || [];
  _imageList.splice(index, 1);
  imagesList.value = $utils.toArray(_imageList);
  emit("change", imagesList.value);
};
</script>

<style scoped>
.upload-list {
  width: 100%;
  margin-top: 20rpx;
  display: flex;
  flex-wrap: wrap;
}
.upload-item-img {
  width: 200rpx;
  height: 200rpx;
  border-radius: var(--base-radius-default);
}
.upload-item {
  width: 200rpx;
  margin-bottom: 20rpx;
  margin-right: calc(33.333333% - 200rpx);
  position: relative;
}
.upload-item-btn {
  width: 200rpx;
  text-align: center;
  line-height: 200rpx;
  border-radius: var(--base-radius-default);
  height: 200rpx;
  border: 1rpx dotted #ddd;
}
.upload-item-btn .icon {
  color: #ddd;
  font-size: 60rpx;
}
.upload-item-del {
  position: absolute;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 40rpx;
  text-align: center;
  line-height: 40rpx;
  color: #fff;
  right: -10rpx;
  top: -10rpx;
  font-size: 20rpx;
}
</style>